
#include <iostream>
#include <string>
#include <cstring>
#include <functional>

#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>


#include "Thread.hpp"
#include "Comm.hpp"

using namespace std;
using namespace ThreadModule;

void Usage(const string proc)
{
    cout << "Usage:\n\t" << proc << " server_ip server_port" << endl;
}

int InitClient(const string &serverip, const uint16_t serverport, struct sockaddr_in *server)
{
    // 1.创建socket文件
    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd < 0)
    {
        cerr << "socket error" << endl;
        return -1;
    }

    // 2.构建目标主机socket信息
    memset(server, 0, sizeof(struct sockaddr_in));
    server->sin_family = AF_INET;
    server->sin_port = htons(serverport);
    server->sin_addr.s_addr = inet_addr(serverip.c_str());

    return sockfd;
}

void recvmessage(int sockfd, string threadname)
{
    int fd=OpenDev("/dev/pts/6",O_RDONLY);
    while(true)
    {
        struct sockaddr_in peer;
        bzero(&peer,sizeof(peer));
        socklen_t len=sizeof(peer);
        char buffer[1024];
        ssize_t n=recvfrom(sockfd,buffer,sizeof(buffer)-1,0,(struct sockaddr*)&peer,&len);
        if(n>0)
        {
            buffer[n]=0;

            write(fd,buffer,sizeof(buffer));
            //printf("%s | %s\n",threadname.c_str(),buffer);//1---stdout
            //将标准输出的消息重定向到/dev/pts/6设备文件中
        }
    }
}
void sendmessage(int sockfd, struct sockaddr_in& server,string threadname)
{

    string message;
    while(true)
    {
        printf("%s|Enter# ",threadname.c_str());
        fflush(stdout);
        getline(cin,message);
        sendto(sockfd,message.c_str(),message.size(),0,(struct sockaddr*)(&server),sizeof(server));
    }
}

//./udpclient serverip serverport
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(1);
    }

    string serverip = argv[1];
    uint16_t serverport = stoi(argv[2]);
    struct sockaddr_in server;
    int sockfd = InitClient(serverip, serverport, &server);
    if (sockfd == -1) return 1;

        
    // 创建两个线程,一个获取消息,一个发送消息
    function<void(string)> recv= std::bind(&recvmessage, sockfd, std::placeholders::_1);
    function<void(string)> send= std::bind(&sendmessage, sockfd, server,std::placeholders::_1);
    Thread Recver(recv, "recver");
    Thread Sender(send, "sender");

    Recver.Start();
    Sender.Start();

    Recver.Join();
    Sender.Join();

    return 0;
}